package com.mall.util.distributed.id;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class IdGeneratorManager {
    private final Map<String, IdGenerator> generatorMap = new ConcurrentHashMap<>();
    private final Function<String, IdGenerator> supplier;

    public IdGeneratorManager() {
        this.supplier = s -> {
            IdGenerator idGenerator;
            ServiceLoader<IdGenerator> idGenerators = ServiceLoader.load(IdGenerator.class);
            Iterator<IdGenerator> iterator = idGenerators.iterator();
            if(iterator.hasNext()) {
                idGenerator = iterator.next();
            }else {
                idGenerator = new SnowFlowerIdGenerator();
            }
            idGenerator.init();
            return idGenerator;
        };
    }

    public void register(String resources) {
        generatorMap.computeIfAbsent(resources, s -> supplier.apply(resources));
    }

    public void register(String... resources) {
        for(String resource : resources) {
            generatorMap.computeIfAbsent(resource, s -> supplier.apply(resource));
        }
    }

    public long nextId(String resource) {
        if(generatorMap.containsKey(resource)) {
            return generatorMap.get(resource).nextId();
        }
        throw new NoSuchElementException(
                "The resource is not registered with the distributed " + "ID resource for the time being.");
    }

    public Map<String, IdGenerator> getGeneratorMap() {
        return generatorMap;
    }
}
